package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: ggm
 * @data 2024年12月11日 20:07
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> getAllAddressBook() {
        //根据userId获取用户地址簿
        Long userId = BaseContext.getCurrentId();
        return addressBookMapper.getByUserId(userId);
    }

    @Override
    public void addAddressBook(AddressBook addressBook) {
        //添加地址簿
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.save(addressBook);
    }

    @Override
    public AddressBook getDefaultAddressBook() {
        //根据userId获取用户地址簿
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBookList = addressBookMapper.getByUserId(userId);
        for (AddressBook addressBook : addressBookList) {
            if(addressBook.getIsDefault()==1){
                return addressBook;
            }
        }
        //用户没有默认地址返回null
        return null;
    }

    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBookMapper.editAddressBook(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);

    }

    @Override
    public void setDefaultAddress(AddressBook addressBook) {
        addressBook.setIsDefault(1);
        addressBookMapper.editAddressBook(addressBook);

    }

    @Override
    public void updateIsDefaultByUserId(AddressBook addressBook) {
        addressBook.setIsDefault(0);;
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);
    }
}
